import type { PagesType } from './types/pages';
import type { QueryType } from './types/index';
import { navigateTo, switchTab, redirectTo, reLaunch } from '.';
import { useUserStoreWithOut } from '@/store/modules/user';

const whiteList: PagesType[] = ['login', 'home', 'contact', 'mine', 'startPage', 'aiChatPage', 'circleDetail']

export const routerValid = (name: PagesType) => !whiteList.includes(name)

/**
 * 路由守卫(跳转前执行)
 * @param name 路由别名
 * @param options 页面参数
 * @returns Promise<any>
 */
export function beforeEach(to: { name: PagesType, options?: QueryType }, routeType: 'navigateTo' | 'switchTab' | 'redirectTo' | 'reLaunch'): Promise<any> {
  return new Promise(async (resolve, reject) => {
    const useUser = useUserStoreWithOut()
    const { Token, userInfo } = storeToRefs(useUser)
    if (whiteList.includes(to.name)) return resolve('success')

    function success() {
      const name = to.name as any
      const options = to.options
      switch (routeType) {
        case 'navigateTo':
          navigateTo({ name, options })
          break;
        case 'switchTab':
          switchTab(name)
          break;
        case 'redirectTo':
          redirectTo({ name, options })
          break;
        case 'reLaunch':
          reLaunch({ name, options })
          break;
      }
    }

    // #ifndef MP
    if (!Token && routerValid(to.name)) {
      navigateTo({ name: 'login', options: { success } })
      reject('未登录')
      return
    }
    // #endif

    // #ifdef MP
    await useUser.wxLogin()
    if (!userInfo.value && routerValid(to.name)) {
      navigateTo({ name: 'login', options: { success } })
      reject('未授权手机号')
      return
    }
    // #endif


    resolve('success');
  });
}

/**
 * 路由跳转后执行
 * @param name 路由别名
 * @param options 页面参数
 * @returns
 */
export function afterEach(name: PagesType, options?: QueryType): void { }

/**
 * 路由跳转错误信息
 * @param name 路由别名
 * @param options 页面参数
 */
export function Error(error: unknown, name: PagesType, options?: QueryType): void {
  console.error(name + ' => ');
  console.error(error);
}
